package tgc.edu.ljc.web.controller;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.ljc.custom.ZtreeUtils;
import tgc.edu.ljc.entity.Dept;
import tgc.edu.ljc.service.DeptService;
import tgc.edu.ljc.web.form.DeptForm;

@Controller
@RequestMapping(value="/ztree")
public class DeptController {
	@Autowired
	private DeptService service;
	
	@RequestMapping(value="/tree")
	public String tree() {
		return "ztree/tree";
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(Integer id) {
		List<Dept> list;
		if(id==null) {
			list = service.findByParentIsNull();
		}else {
			list=service.findByParentId(id);
		}
		return ZtreeUtils.buildZtreeResult(list);
	}
	
	@RequestMapping(value="/edit")
	public String edit(Integer id,ModelMap map) {
		Dept model = service.findById(id);
		map.put("model", model);
		return "ztree/edit";
	}
	
	@RequestMapping(value="/save")
	public String save(DeptForm form) {
		Dept model=new Dept();
		BeanUtils.copyProperties(form, model,"parent");
		Dept parent = service.findById(form.getpId());
		model.setParent(parent);
		service.save(model);
		return "redirect:tree";
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(Integer id) {
		service.deleteById(id);
		return "OK";
	}
	
	@RequestMapping(value="/rename")
	@ResponseBody
	public Object rename(Integer id,String name,Integer pId) {
		service.rename(id,name,pId);
		return "OK";
	}
	
	@RequestMapping(value="/add")
	@ResponseBody
	public Object add(Integer pId) {
		Dept model=service.add(pId);
		return model;
	}
}
